package Stack;
import java.util.Stack;

public class bracketsMatch {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        char[] ch = s.toCharArray();
        for(int i = 0 ; i < s.length() ; i++){
            if(isLeft(ch[i])){
                //左括号直接入栈
                stack.push(ch[i]);
            }else{
                if(!stack.empty() && isMatch(stack.peek(),ch[i])){
                    //碰到右括号且和左括号匹配
                    stack.pop();
                }else{
                    //碰到右括号且和左括号不匹配
                    return false;
                }
            }
        }
        return stack.empty() ;
    }

    public boolean isLeft(char ch){
        if(ch == ('(') || ch == ('[') || ch == ('{') ){
            return true;
        }
        return false;
    }

    public boolean isMatch(char peek,char ch){
        if( peek == '(' && ch == ')' ){
            return true;
        }else if ( peek == '[' && ch == ']'){
            return true;
        }else if( peek == '{' && ch == '}'){
            return true;
        }else{
            return false;
        }
    }
}